from sc_engine.messaging.transports import (
    MessagelessRetrievalContext, MessageRetrievalContext, ITransport
)

class LocalTransport(ITransport):
    """A transport that is completely contained in memory.
    """
    def __init__(self):
        self.subscriptions = {}
        self.inboxes = {}

    def add_queue(self, queue_name):
        self.subscriptions[queue_name] = set()
        self.inboxes[queue_name] = []

    def subscribe(self, queue_name, message_type):
        self.subscriptions[queue_name].add(message_type)

    def send(self, msg):
        message_type = type(msg)

        for queue_name, subscriptions in self.subscriptions.items(): 
            if message_type in subscriptions:
                self.inboxes[queue_name].append(msg)

    def retrieve(self, queue_name):
        if len(self.inboxes[queue_name]) == 0:
            return MessagelessRetrievalContext()

        msg = self.inboxes[queue_name][0]
        on_completion = self.inboxes[queue_name].pop()
        return MessageRetrievalContext(msg, on_completion)

    def close(self):
        pass
